# Copyright (C) 2007 Jason Kivlighn
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, #USA.

import colorsys as c
import random

def colorize_random(artist_stack):
  color_stack = {}
  
  for artist in artist_stack:
    color_stack[artist] = (random.random(),random.random(),random.random())
  
  return color_stack
  
def colorize_hsv_trans(artist_stack,begin,end):
  color_stack = {}
  
  unrolled_stack = []
  for i in range(len(artist_stack)):
    if len(artist_stack)/2 <= i:
      if len(artist_stack) % 2 == 1:
        unrolled_stack.append(artist_stack[i])
      break
    unrolled_stack.append(artist_stack[i])
    unrolled_stack.append(artist_stack[-(i+1)])
  unrolled_stack.reverse()
  
  i = 0
  for artist in unrolled_stack:
    color_stack[artist] = hsv_trans(begin,end,i,len(unrolled_stack))
    i += 1
  
  return color_stack


def brighten(rgb):
  h, s, v = c.rgb_to_hsv(*rgb)
  return c.hsv_to_rgb(h,s*3.0/4,v)

def load_bbr_table():
  table = []
  f = open("bbr_rgb.txt","r")
  for s in f.xreadlines():
    table.append(map(float,s.split(" ")))
  table.reverse()
  return table

def rgb_trans(begin,end,i,total):
  return (begin[0]+i*(end[0]-begin[0])/total,
    begin[1]+i*(end[1]-begin[1])/total,
    begin[2]+i*(end[2]-begin[2])/total)
    
def hsv_trans(begin,end,i,total):
  total=float(total)
  rgb = c.hsv_to_rgb(begin[0]+i*(end[0]-begin[0])/total,
     begin[1]+i*(end[1]-begin[1])/total,
     begin[2]+i*(end[2]-begin[2])/total)
  if i != 0 and ((i+2) % 4 == 0 or (i+3) % 4 == 0):
    return brighten(rgb)
  else:
    return rgb
    
def random_colors(r_wgt=1,g_wgt=1,b_wgt=1):
  sum = float(r_wgt+g_wgt+b_wgt)
  return (random.random()*r_wgt/sum*3,random.random()*g_wgt/sum*3,random.random()*b_wgt/sum*3)

def trans_table(table,i,total):
  if i == 0:
    return table[i*len(table)/total]
  elif i % 4 == 0 or (i+1) % 4 == 0:
    r, g, b = table[i*len(table)/total]
    r += (1-r)/2
    g += (1-g)/2
    b += (1-b)/2
    return (r,g,b)
  else:
    return table[i*len(table)/total]
